import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { DownOutlined, PlusOutlined,InfoCircleOutlined } from '@ant-design/icons';
import { Input, Modal, InputNumber, Upload, Button, Icon, Select, Radio, Card,Row, Col, Divider,message,Tooltip} from 'antd';
import { formatMessage,FormattedMessage } from 'umi-plugin-react/locale';
import { FormComponentProps } from '@ant-design/compatible/es/form';
import React, { useState } from 'react';
import { queryRule, updateRule, addRule, removeRule } from '../service';
import styles from '../style.less';

// 导入自定义组件1
import PreviewForm from '@/components/PreviewForm';
import * as BdHelper from '@/utils/BdHelper';
import * as DataHelper from '@/helpers/DataHelper';
import * as TsxHelper from '@/helpers/TsxHelper';

// 常量
const { TextArea } = Input;
const FormItem = Form.Item;

// 定义: 数据表单属性
interface DataFormProps extends FormComponentProps {
  // dataModalVisible: boolean;
  isUpdate: boolean
  dataFormValues: any
  common: any
}

// 数据表单
const DataForm: React.FC<DataFormProps> = props => {
  // 组件属性
  const { form, common, isUpdate,dataFormValues } = props;

  // 图片状态
  const [picture, setPicture] = useState<any[]>([]);
  const [uploadChanged, setUploadChanged] = useState<boolean>(false);
  const [pictureLogo, setPictureLogo] = useState<any[]>([]);
  const [uploadLogoChanged, setUploadLogoChanged] = useState<boolean>(false);
  const [previewModelVisible, handlePreviewModalVisible] = useState<boolean>(false);
  const [previewImg, setPreviewImg] = useState('');

  //提交表单
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      if(picture.length > 0){
        fieldsValue.file_id   = picture[0].file_id
        fieldsValue.file_url  = picture[0].file_url
      }
      
      console.log("submit fields ", fieldsValue)
      var submitValue = [
          {
            "alias_key": 'send',
            "item_type":'system',
            "dict_item_arr": [
              {
                "alias_key": "send_email_from_name",
                "item_value": fieldsValue.send_email_from_name,
                'item_type':"text",
              },
              {
                "alias_key": "send_email_from_mail",
                "item_value": fieldsValue.send_email_from_mail,
                'item_type':"email",
              },
              {
                "alias_key": "send_email_service",
                "item_value":fieldsValue.send_email_service,
                'item_type':"select",
              },
              {
                "alias_key": "send_sms_service",
                "item_value": fieldsValue.send_sms_service,
                'item_type':"select",
              },
              {
                "alias_key": "send_sms_code",
                "item_value": fieldsValue.send_sms_code,
                'item_type':"select",
              },
              {
                "alias_key": "send_sms_code_more",
                "item_value": fieldsValue.send_sms_code_more.split('\n'),
                'item_type':"array",
              },
              {
                "alias_key": "send_ios_service",
                "item_value": fieldsValue.send_ios_service,
                'item_type':"text",
              },
              {
                "alias_key": "send_android_service",
                "item_value": fieldsValue.send_android_service,
                'item_type':"text",
              },
              {
                "alias_key": "send_wechat_service",
                "item_value": fieldsValue.send_wechat_service,
                'item_type':"text",
              },
            ]
          },
      ]
      // 如果更新成功之后，重置表单
      updateRule({config_json: JSON.stringify(submitValue)}).then((res:any) => {
        console.log('handleSubmit then success is ', JSON.stringify(submitValue))
        if(res.code == 0){
          message.success('保存成功')
          // form.resetFields()
        }else{
          message.error(res.message);
        }
      })

    });
  };

  // 设置上传文件值
  const setUploadFile = (fileList:any) => {
    setUploadChanged(true)
    let fileArr = DataHelper.getLastUploadFile(fileList)
    console.log("fileArr is ", fileArr)
    if(fileArr.length > 0){
      setPicture(fileArr)
      setPreviewImg(fileArr[0].file_url)
    }else if(fileArr.length === 0){
      console.log('set picture []')
      setPicture([])
    }
  }

    // 设置Logo上传文件值
    const setLogoUploadFile = (fileList:any) => {
      setUploadLogoChanged(true)
      let fileArr = DataHelper.getLastUploadFile(fileList)
      console.log("fileArr is ", fileArr)
      if(fileArr.length > 0){
        setPictureLogo(fileArr)
        setPreviewImg(fileArr[0].file_url)
      }else if(fileArr.length === 0){
        console.log('set picture []')
        setPictureLogo([])
      }
    }

    const parseData = (key:any,options:any) => {
      // console.log(options);
      var name:any = "";
      if(Array.isArray(options) && options.length>0){
        options.map(item=>{
          if(item.alias_key == key){
            name = item?.item_value;
          }
        })
      }
      return name
    }

  // 初始化变量
  const token = BdHelper.getBdToken()

  // 编辑时初始化 picture
  const defaultPicture = DataHelper.buildFileByUrl(dataFormValues.site_icon)
  const defaultLogoPicture = DataHelper.buildFileByUrl(dataFormValues.site_logo)

  // 是否展示图片上传按钮
  const showUploadButton = DataHelper.showUploadBtn(isUpdate, picture, defaultPicture, uploadChanged)
  const showUploadLogoButton = DataHelper.showUploadBtn(isUpdate, pictureLogo, defaultLogoPicture, uploadLogoChanged)
  

  // 弹出框
  // @ts-ignore
  return <div>
        <Card title={formatMessage({ id: 'emailconfig' })} className={styles.card} bordered={false}>
            <Form layout="vertical" hideRequiredMark>
              <Row gutter={16}>
                <Col lg={6} md={12} sm={24}>
                  <FormItem  label={formatMessage({ id: 'email_service' })}>
                      {form.getFieldDecorator('send_email_service', {
                        initialValue: parseData('send_email_service',dataFormValues),
                        // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
                      })(<Select placeholder={formatMessage({ id: 'app.base.please_select' })} size={'default'} style={{ width: '100%' }}>
                      {common?.emailOption  && TsxHelper.buildSelectOption(common?.emailOption )}
                    </Select>)}
                  </FormItem>
                </Col>
                {/* <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
                  <FormItem  label={formatMessage({ id: 'email_from_mail' })}>
                    {form.getFieldDecorator('send_email_from_mail', {
                      initialValue: parseData('send_email_from_mail',dataFormValues),
                      rules: [{ pattern:  /^([a-zA-Z0-9_-]{1,16})@([a-zA-Z0-9]{1,9})(\.[a-zA-Z0-9]{1,9}){0,3}(\.(?:com|net|org|edu|gov|mil|cn|us)){1,4}$/, message: '请输入合法邮箱', }],
                    })(<Input  placeholder={formatMessage({ id: 'app.base.please_input' })}/>)}
                  </FormItem>
                </Col>
                <Col xl={{ span: 8, offset: 2 }} lg={{ span: 10 }} md={{ span: 24 }} sm={24}>
                  <FormItem label={formatMessage({ id: 'email_from_name' })}>
                    {form.getFieldDecorator('send_email_from_name', {
                      initialValue: parseData('send_email_from_name',dataFormValues),
                      // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
                    })(<Input placeholder={formatMessage({ id: 'app.base.please_input' })}/>)}
                  </FormItem>
                </Col> */}
              </Row>
            </Form>
          </Card>
    <Card title={formatMessage({ id: 'smsconfig' })} className={styles.card} bordered={false}>
      <Form layout="vertical" hideRequiredMark>
        <Row gutter={16}>
          <Col lg={6} md={12} sm={24}>
            <FormItem label={formatMessage({ id: 'sms_service' })}>
              {form.getFieldDecorator('send_sms_service', {
                initialValue: parseData('send_sms_service',dataFormValues),
                // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
              })(<Select placeholder={formatMessage({ id: 'app.base.please_select' })} size={'default'} style={{ width: '100%' }}>
              {common?.smsOption && TsxHelper.buildSelectOption(common?.smsOption)}
              </Select>)}
            </FormItem>
          </Col>
          <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
            <FormItem label={formatMessage({ id: 'sms_code' })}>
              {form.getFieldDecorator('send_sms_code', {
                initialValue: parseData('send_sms_code',dataFormValues),
                // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
              })(<Input placeholder={formatMessage({ id: 'app.base.please_input' })}/>)}
            </FormItem>
          </Col>
          <Col xl={{ span: 8, offset: 2 }} lg={{ span: 10 }} md={{ span: 24 }} sm={24}>
            <FormItem label={formatMessage({ id: 'sms_code_more' })}>
              {form.getFieldDecorator('send_sms_code_more', {
                initialValue: parseData('send_sms_code_more',dataFormValues).replace(/n|rn/g,'\n'),
                // rules: [],&#13; dangerouslySetInnerHTML={{__html: '+87<br/>+88'}}
              })(<TextArea  wrap="hard" style={{width: '100%',whiteSpace: 'pre-wrap',wordWrap: 'break-word'}}  rows={4} cols={30} placeholder={'一行一个，前面必须带 + 号留空代表只支持单一国家需短信服务商支持国际短信功能'} ></TextArea>)}
            </FormItem>
          </Col>
        </Row>
      </Form>
    </Card>

    <Card title={formatMessage({id: 'Client push configuration'})} className={styles.card} bordered={false}>
      <Form layout="vertical" hideRequiredMark>
        <Row gutter={16}>
          <Col lg={6} md={12} sm={24}>
            <FormItem label={
              <span>
                <FormattedMessage id="iOS" />
                <em className={styles.optional}>
                  <Tooltip title={<FormattedMessage id=" iOS 系统弹窗通知功能" />}>
                    <InfoCircleOutlined style={{ marginRight: 4,marginLeft: 4 }} />
                  </Tooltip>
                </em>
              </span>
            }>
              {form.getFieldDecorator('send_ios_service', {
                initialValue: parseData('send_ios_service',dataFormValues),
                // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
              })(<Select placeholder={formatMessage({ id: 'app.base.please_select' })} size={'default'} style={{ width: '100%' }}>
              {common?.iosOption && TsxHelper.buildSelectOption(common?.iosOption)}
              </Select>)}
            </FormItem>
          </Col>
          <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
            <FormItem label={
              <span>
                <FormattedMessage id="Android" />
                <em className={styles.optional}>
                  <Tooltip title={<FormattedMessage id="Android 系统弹窗通知功能。" />}>
                    <InfoCircleOutlined style={{ marginRight: 4,marginLeft: 4 }} />
                  </Tooltip>
                </em>
              </span>
            }>
              {form.getFieldDecorator('send_android_service', {
                initialValue: parseData('send_android_service',dataFormValues),
                // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
              })(<Select placeholder={formatMessage({ id: 'app.base.please_select' })} size={'default'} style={{ width: '100%' }}>
              {common?.androidOption && TsxHelper.buildSelectOption(common?.androidOption)}
              </Select>)}
            </FormItem>
          </Col>
          <Col xl={{ span: 8, offset: 2 }} lg={{ span: 10 }} md={{ span: 24 }} sm={24}>
            <FormItem label={
              <span>
                <FormattedMessage id="weChat" />
                <em className={styles.optional}>
                  <Tooltip title={<FormattedMessage id="微信服务通知或者公众号模板消息。" />}>
                    <InfoCircleOutlined style={{ marginRight: 4,marginLeft: 4 }} />
                  </Tooltip>
                </em>
              </span>
            }>
              {form.getFieldDecorator('send_wechat_service', {
                initialValue: parseData('send_wechat_service',dataFormValues),
                // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
              })(<Select placeholder={formatMessage({ id: 'app.base.please_select' })} size={'default'} style={{ width: '100%' }}>
              {common?.wechatOption && TsxHelper.buildSelectOption(common?.wechatOption)}
              </Select>)}
            </FormItem>
          </Col>
        </Row>
      </Form>
    </Card>

    {/* <Card title={formatMessage({ id: 'Android 配置' })} className={styles.card} bordered={false}>
      <Form layout="vertical" hideRequiredMark>
        <Row gutter={16}>
          
        </Row>
      </Form>
    </Card>

    <Card title={formatMessage({ id: 'wechatconfig' })} className={styles.card} bordered={false}>
      <Form layout="vertical" hideRequiredMark>
        <Row gutter={16}>
          
        </Row>
      </Form>
    </Card> */}

    <Col span={24}>
      <div style={{display: 'flex',justifyContent:'center',marginTop:20,}}>
        <Button type="primary" style={{marginLeft:30}} onClick={()=>{okHandle()}}>提交保存</Button>
        {/* <Button type="default" style={{marginLeft:30}}>发信测试</Button> */}
      </div>
    </Col>
    {
      previewModelVisible && (
        <PreviewForm
          previewModelVisible={previewModelVisible}
          onVisibleModel={handlePreviewModalVisible}
          previewImg={previewImg}
        />
      )
    }
  </div>;
};

export default Form.create<DataFormProps>()(DataForm);
